//
//  CYQRCode.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/9/25.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYQRCode.h"

@implementation CYQRCode
+ (UIImage *)QRCodeWithUrlString:(NSString *)url{
    if (!url)
        return nil;
    //创建一个二维码滤镜对象
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    //恢复滤镜的默认属性
    [filter setDefaults];
    // 将字符串转转码 换成NSData,
    NSData *imagedata = [url dataUsingEncoding:NSUTF8StringEncoding];
    //通过kvo方式给一个字符串，生成二维码
    [filter setValue:imagedata forKey:@"inputMessage"];
    //设置容错等级
    [filter setValue:@"M" forKey:@"inputCorrectionLevel"];
    //获得滤镜输出图像
    CIImage *outputImage = [filter outputImage];
    //把模糊图像转化成清晰图像
    return  [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:200];
}

+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

@end
